<template>
  <div>
    <n-button size="medium" @click="clear(), (disabled = true)">充值</n-button>
    <n-modal v-model:show="disabled" :mask-closable="false" preset="dialog" title="充值">
      <n-form
        :label-width="80"
        :model="formValue"
        :rules="rules"
        size="medium"
        ref="formRef"
        label-placement="left"
      >
        <n-form-item label="充值金额：" path="money">
          <n-input
            v-model:value="formValue.money"
            placeholder="输入充值的金额 "
            :show-button="false"
            style="width: 100%"
            type="number"
          />
        </n-form-item>
        <n-form-item style="margin-top: 18px; margin-bottom: 10px">
          充值方式 ：&nbsp;&nbsp;
          <n-dropdown @select="handleSelect" trigger="click" :options="options">
            <n-button>{{ payWay }}</n-button>
          </n-dropdown>
          <span style="width: 50%; color: red; font-size: 8px">
            <n-tooltip trigger="click">
              <template #trigger>
                <n-button @click="exchangeRate" class="button">?</n-button>
              </template>
              {{
                `当前充值换算汇率为:${paritiesByBank}预计${hourByBank}小时后到账，预计产生手续费${serviceChargeByBank}`
              }}
            </n-tooltip>
          </span>
        </n-form-item>
        <n-form-item label="付款币种：" path="ccy" style="margin-top: 18px">
          <n-select
            placeholder="请选付款币种"
            :options="userOptions"
            v-model:value="formValue.ccy"
          />
        </n-form-item>
        <n-form-item
          label="付款账号："
          path="account"
          style="margin-top: 18px; margin-bottom: 18px"
        >
          <n-input v-model:value="formValue.account" placeholder="输入付款账号 " disabled />
        </n-form-item>
        <n-form-item path="password" label="交易密码：" style="margin-bottom: 18px">
          <n-input
            v-model:value="formValue.password"
            type="password"
            placeholder="输入交易密码 "
            maxlength="6"
          />
        </n-form-item>
        <n-space justify="right">
          <n-form-item>
            <n-space>
              <n-button @click="(disabled = false), clear()" size="medium" strong secondary
                >取消</n-button
              >
              <n-button
                @click="Submit"
                attr-type="button"
                size="medium"
                type="info"
                :disabled="isShow"
                >确认</n-button
              >
            </n-space>
          </n-form-item>
        </n-space>
      </n-form>
    </n-modal>
  </div>
</template>
<script lang='ts' setup>
import { ref, defineComponent } from 'vue';
import { useMessage } from 'naive-ui';
import { recharge } from '@/api/recharge/recharge'; //充值
import { createStorage } from '@/utils/Storage';
import { getChainwallet } from '@/api/wthdrawalApply/getChainwallet'; // 连钱包

import md5 from 'js-md5';
import { getExchangeRate } from '@/api/exchangeRate/exchangeRate'; // 当前汇率

const Storage = createStorage({ storage: localStorage });

const message = useMessage();

const userOptions = [
  {
    value: 'HPC',
    label: '和平币',
  },
];

const isShow = ref(false);
const disabled = ref(false); // 是否显示模态框

const formRef = ref();

const paritiesByBank = ref('--'); // 银行账户充值汇率

const hourByBank = ref('24'); // 银行账户充值到账时间

const serviceChargeByBank = ref('--'); // 银行账户充值手续费

const paritiesByLink = ref('2222:2222'); // 链钱包汇率

const hourByLink = ref('22222'); // 链钱包到账时间

const serviceChargeByLink = ref('222222'); // 链钱包手续费

let custNoValue = Storage.get('custNo');

const rechargeParm = ref({
  custNo: custNoValue,
  amount: '',
  password: '',
  rechargeMode: '01',
  // operator: '',
  ccy: '请选择付款币种',
});

const options = ref([
  {
    label: '链钱包充值',
    key: '01',
  },
]);

const payWay = ref('请选择充值方式');

async function handleSelect(key, val) {
  rechargeParm.value.rechargeMode = key;
  message.info(val.label);
  payWay.value = val.label;
  if ((payWay.value = '链钱包充值')) {
    let res = await getChainwallet();
    console.log(res);
    formValue.value.account = res.data.body.address;
  }
}
// 清除输入框
const clear = () => {
  formValue.value.money = '';
  formValue.value.account = '';
  formValue.value.password = '';
  payWay.value = '请选择充值方式';
  formValue.value.ccy = '请选择付款币种';
};

// 表单验证规则
const rules = {
  money: {
    required: true,
    validator(rule, value) {
      if (!value) {
        return new Error('请输入充值金额');
      } else {
        return true;
      }
    },
    message: '请输入充值金额',
    trigger: 'blur',
  },
  account: {
    required: true,
    message: '请输入付款账号',
    trigger: 'blur',
  },
  password: {
    required: true,
    message: '请输入密码',
    trigger: 'blur',
  },
};

const formValue = ref({
  money: '',
  account: '',
  password: '',
  ccy: '',
  sysSign: '0',
});

const rateValue = ref({
  amt: '',
  feeType: '3',
});
// 获取当前充值汇率
async function exchangeRate() {
  if (formValue.value.money) {
    rateValue.value.amt = formValue.value.money;
    await getExchangeRate(rateValue.value).then((val) => {
      console.log(val);
      paritiesByBank.value = val.data.body.excRate;
      serviceChargeByBank.value = val.data.body.commissionAmount;
    });
  } else {
    message.info('查看汇率前，请先输入充值金额');
  }
}

// 验证结果输出
const Submit = (e) => {
  isShow.value = true;
  formRef.value.validate((errors) => {
    console.log(formValue.value);
    if (!errors) {
      rechargeParm.value.account = formValue.value.account;
      rechargeParm.value.amount = formValue.value.money;
      rechargeParm.value.password = formValue.value.password;
      rechargeParm.value.ccy = formValue.value.ccy;
      rechargeParm.value.sysSign = formValue.value.sysSign;
      if (rechargeParm.value.amount < 0) {
        message.error('充值金额不可为负数');
        isShow.value = false;
      } else {
        if (!rechargeParm.value.ccy) {
          message.error('请选择付款币种');
          isShow.value = false;
        } else {
          rechargeParm.value.password = md5(rechargeParm.value.password);
          recharge(rechargeParm.value).then((val) => {
            clear();
            console.log(val);
            if (val.data.sysHead.retCd !== '000000') {
              message.error(val.data.sysHead.retInf);
              isShow.value = false;
            } else {
              message.success('充值成功');
              clear();
              isShow.value = false;
              disabled.value = false;
            }
          });
        }
      }
    } else {
      message.error('充值失败');
      isShow.value = false;
    }
  });
};
</script>
<style lang="less">
.button {
  width: 20px;
  height: 20px;
  padding: 0 !important;
  margin-left: 8px;
  border-radius: 10px;
}
</style>